package com.youi.job;

import com.google.common.collect.Maps;
import com.youi.common.Common;
import com.youi.common.DelStatus;
import com.youi.common.OrderStatusEnum;
import com.youi.entity.Userorder;
import com.youi.service.UserorderService;
import com.youi.service.impl.TransactionalUserorderService;
import com.youi.util.DateUtil;
import com.youi.util.LogUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @description: 订单相关异步定时任务
 * @Author: winty
 * @Date: 2020/5/27 11:11
 */
@Component
public class OrderJob {

    @Autowired
    private UserorderService userorderService;

    @Autowired
    private TransactionalUserorderService transactionalUserorderService;

    /**
     * 超过15分钟未支付,自动取消订单
     * 每分钟执行一次
     * TODO
     *
     * @throws IOException
     */
    //@Async
    //@Scheduled(cron = "0 */1 * * * ?")
    public void autoCancelUserOrder() throws IOException {
        Map<String, Object> params = Maps.newHashMap();
        params.put(Common.DELSTATUS, DelStatus.NODEL);
        params.put(Common.STATUS, OrderStatusEnum.TO_PAY.getKey());

        Map<String, Object> ltParam = Maps.newHashMap();
        ltParam.put("gmtOrder", DateUtil.getCalendarByAdd(new Date(), Calendar.MINUTE, -16));

        //超过15分钟未支付订单
        List<Userorder> userOrderList = userorderService.getByParamsAll(params, null, null, null, ltParam);
        if (CollectionUtils.isEmpty(userOrderList)) {
            return;
        }
        userOrderList.stream().forEach(userOrder -> {
            try {
                transactionalUserorderService.cancelUserOrder(userOrder, 1);
            } catch (Exception e) {
                LogUtil.Error("****订单定时任务****自动取消订单[" + userOrder.getOrderNo() + "]失败：" + e.getMessage());
            }
        });
    }
}